package com.wl.controller;

import com.wl.model.NewsCategory;
import com.wl.model.NewsInfo;
import com.wl.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RequestMapping("/category")
@Controller
public class CategoryController {
    @Autowired
    CategoryService categoryService;


    @PostMapping("list")
    public ModelAndView list(NewsCategory category, HttpServletRequest request) throws UnsupportedEncodingException {
        request.getSession().setAttribute("categoryList", categoryService.list(category.getTitle(), category.getCategoryId()));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("categoryManage");
        return modelAndView;
    }

    @GetMapping("findById")
    public ModelAndView findById(Long categoryId, HttpServletRequest request) throws UnsupportedEncodingException {
        request.getSession().setAttribute("category", categoryService.findById(categoryId));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("addAndUpdateNewsCategory");
        modelAndView.addObject("isUpdate","update");
        return modelAndView;
    }

    @GetMapping("del")
    public ModelAndView del(Long categoryId, HttpServletRequest request) throws UnsupportedEncodingException {
        categoryService.delById(categoryId);
        request.getSession().setAttribute("categoryList", categoryService.list("", null));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("categoryManage");
        return modelAndView;
    }

    @PostMapping("add")
    public ModelAndView add(NewsCategory category, HttpServletRequest request) throws UnsupportedEncodingException {
        categoryService.add(category);
        request.getSession().setAttribute("categoryList", categoryService.list("", null));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("categoryManage");
        return modelAndView;
    }

    @PostMapping("updateById")
    public ModelAndView updateById(NewsCategory category, HttpServletRequest request) throws UnsupportedEncodingException {
        categoryService.updateById(category);
        request.getSession().setAttribute("categoryList", categoryService.list("", null));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("categoryManage");
        return modelAndView;
    }
}
